class BarometricPressureSensorModule {
  constructor(deviceId) {
    this.topic = 'device/barometric-pressure'; // 大气压数据发布主题
    this.minPressure = 980; // 最低大气压（hPa）
    this.maxPressure = 1050; // 最高大气压（hPa）
    this.interval = 5000; // 发送间隔（毫秒）
    this.timer = null; // 定时器引用
    this.currentPressure = 0; // 当前大气压
    this.deviceId = deviceId;
  }

  // 初始化大气压传感器模块
  async init(mqttConnector) {
    this.mqttConnector = mqttConnector;
    console.log('大气压传感器模块已初始化');
    this.generateInitialPressure();
  }

  // 生成初始大气压
  generateInitialPressure() {
    this.currentPressure = parseFloat(
      (Math.random() * (this.maxPressure - this.minPressure) + this.minPressure).toFixed(2)
    );
  }

  // 生成波动的大气压值
  generateFluctuatedPressure() {
    // 随机波动范围为±1 hPa
    const fluctuation = (Math.random() - 0.5) * 2;
    let newPressure = this.currentPressure + fluctuation;

    // 确保大气压在范围内
    if (newPressure < this.minPressure) {
      newPressure = this.minPressure;
    } else if (newPressure > this.maxPressure) {
      newPressure = this.maxPressure;
    }

    this.currentPressure = parseFloat(newPressure.toFixed(2));
    return this.currentPressure;
  }

  // 开始发送大气压数据
  startSending() {
    if (this.timer) {
      console.log('大气压数据发送已在运行中');
      return;
    }

    console.log('开始发送大气压数据');
    this.sendPressure(); // 立即发送一次
    this.timer = setInterval(() => {
      this.sendPressure();
    }, this.interval);
  }

  // 发送大气压数据
  async sendPressure() {
    const pressure = this.generateFluctuatedPressure();
    const pressureMessage = {
      deviceId: this.deviceId,
      timestamp: Date.now(),
      type: 'sensor-data',
      data: {
        value: pressure+"",
        unit: 'hPa',
        status: 'normal'
      }
    };
    await this.mqttConnector.publish(this.topic, JSON.stringify(pressureMessage));
  }

  // 停止发送大气压数据
  stopSending() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
      console.log('停止发送大气压数据');
    }
  }

  // 设置大气压范围
  setPressureRange(min, max) {
    this.minPressure = min;
    this.maxPressure = max;
    console.log(`大气压范围已设置: ${min}hPa - ${max}hPa`);
  }

  // 设置发送间隔
  setInterval(interval) {
    this.interval = interval;
    console.log(`发送间隔已设置: ${interval}ms`);

    // 如果正在发送，则重新启动定时器
    if (this.timer) {
      this.stopSending();
      this.startSending();
    }
  }
}

module.exports = BarometricPressureSensorModule;